﻿using AutoMapper;
using MediatR;
using Notification.API.Application.Controller.Notification;
using Notification.Errorcode;
using Notification.Errorcode.ErrorCode;
using Notification.Infrasturcture.Interfaces;
using Notification.Infrasturcture.Repositorys;

namespace Notification.API.Application.CommandHandler.Notifications
{
    public class UpdateNotificationCommandHandler : IRequestHandler<UpdNotificationCommand, ApiResult>
    {
        private readonly IUpdateProductDetailsRepository updateProductDetailsRepository;

        private readonly IMapper mapper;

        private readonly ILogger<UpdateNotificationCommandHandler> logger;

        public UpdateNotificationCommandHandler(IUpdateProductDetailsRepository updateProductDetailsRepository, IMapper mapper, ILogger<UpdateNotificationCommandHandler> logger)
        {
            this.updateProductDetailsRepository = updateProductDetailsRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(UpdNotificationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询生产工单
                var updateNotification = await updateProductDetailsRepository.GetAsync(c => c.Productid == request.Productid);
                if (updateNotification == null)
                {
                    return ApiResult.Fail("修改当前数据不存在", StatusCodeEnum.BadRequest);
                }

                // 更新生产工单
                var productionPlan = mapper.Map(request, updateNotification);
                await updateProductDetailsRepository.UpdateAsync(productionPlan);

                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "生产工单修改失败");
                throw;
            }
        }
    }
}